import { _decorator, BufferAsset, Component, Node, sys } from 'cc';
import IService from '../extensions/xworker/assets/IService';
import WorkerSevices from '../extensions/xworker/assets/WorkerService';
import { getWorkerImplUrl } from './WorkerImpl';
const { ccclass, property } = _decorator;

interface CallRet {
    userData: string
    ret: string
    error: string
    showMsg: string
    boardUpdate: string
    prePayCheckRet: string
    orderIds: string
}

class LocalWorkerService implements IService<string> {
    private readonly worker: WorkerSevices<string>
    private readonly initPromise: Promise<void>
    constructor() {
        this.worker = new WorkerSevices()
        this.initPromise = this.worker.Init(getWorkerImplUrl(), null, null)
    }

    get IsValid(): boolean {
        return this.worker.IsValid
    }

    private _requestInternal<TRsp, TReq>(cmd: string, data: TReq, resolve: (resp: TRsp) => void, reject: (err: string) => void) {
        let userData: string = sys.localStorage.getItem('local_player_data')
        if (!userData || userData.length <= 0) userData = ''
        let params: string | null = null
        if (data) params = JSON.stringify(data)
        this.worker.request(cmd, { params, userData }).then((resp: string) => {
            console.log('Worker response:::: ', resp)
            const data = JSON.parse(resp) as CallRet
            if (data.error) {
                reject(data.error)
                return
            }
            if (data.userData) {
                sys.localStorage.setItem('local_player_data', data.userData)
            }
            resolve(JSON.parse(data.ret) as TRsp)
        }).catch(reject)
    }

    request<TRsp, TReq>(cmd: string, data?: TReq): Promise<TRsp> {
        return new Promise<TRsp>((resolve, reject) => {
            if (this.IsValid) {
                this._requestInternal(cmd, data, resolve, reject)
            } else {
                this.initPromise.then(() => {
                    this._requestInternal(cmd, data, resolve, reject)
                }).catch(reject)
            }
        })
    }
}


@ccclass('TestWorker')
export class TestWorker extends Component {
    start() {
        const service = new LocalWorkerService()
        service.request("getRoleData").then((resp)=>{
            console.log('getRoleData', resp)
        })
    }

    update(deltaTime: number) {

    }
}

